Page({
  data: {
    currentTool: 'brush',
    currentColor: '#000000',
    lineWidth: 4,
    showColorPicker: false,
    showSizePicker: false,
    colors: ['#000000', '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'],
    lineWidths: [2, 4, 6, 8, 12, 16, 20],
    startX: 0,
    startY: 0,
    isDrawing: false,
    scale: 1,
    lastScale: 1
  },

  onLoad: function() {
    this.initCanvas();
  },

  async initCanvas() {
    const query = wx.createSelectorQuery();
    query.select('#paintCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        // 设置画布大小
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr);
        
        this.canvas = canvas;
        this.ctx = ctx;
        
        // 设置初始样式
        this.ctx.strokeStyle = this.data.currentColor;
        this.ctx.lineWidth = this.data.lineWidth;
        this.ctx.lineCap = 'round';
        this.ctx.lineJoin = 'round';
      });
  },

  touchStart(e) {
    const { x, y } = e.touches[0];
    if (e.touches.length === 2) {
      // 双指触摸，准备缩放
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      this.startDistance = Math.sqrt(
        Math.pow(touch2.x - touch1.x, 2) + 
        Math.pow(touch2.y - touch1.y, 2)
      );
    } else {
      // 单指触摸，准备绘画
      this.setData({
        startX: x,
        startY: y,
        isDrawing: true
      });
    }
  },

  touchMove(e) {
    if (e.touches.length === 2) {
      // 双指触摸，进行缩放
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const currentDistance = Math.sqrt(
        Math.pow(touch2.x - touch1.x, 2) + 
        Math.pow(touch2.y - touch1.y, 2)
      );
      
      const scale = (currentDistance / this.startDistance) * this.data.lastScale;
      this.setData({
        scale: Math.min(Math.max(scale, 0.5), 3)
      });
    } else if (this.data.isDrawing) {
      // 单指触摸，进行绘画
      const { x, y } = e.touches[0];
      const ctx = this.ctx;
      
      switch (this.data.currentTool) {
        case 'brush':
          ctx.beginPath();
          ctx.moveTo(this.data.startX, this.data.startY);
          ctx.lineTo(x, y);
          ctx.stroke();
          break;
          
        case 'eraser':
          ctx.save();
          ctx.strokeStyle = '#FFFFFF';
          ctx.lineWidth = this.data.lineWidth * 2;
          ctx.beginPath();
          ctx.moveTo(this.data.startX, this.data.startY);
          ctx.lineTo(x, y);
          ctx.stroke();
          ctx.restore();
          break;
          
        case 'line':
          this.clearCanvas();
          ctx.beginPath();
          ctx.moveTo(this.data.startX, this.data.startY);
          ctx.lineTo(x, y);
          ctx.stroke();
          break;
          
        case 'circle':
          this.clearCanvas();
          const radius = Math.sqrt(Math.pow(x - this.data.startX, 2) + Math.pow(y - this.data.startY, 2));
          ctx.beginPath();
          ctx.arc(this.data.startX, this.data.startY, radius, 0, Math.PI * 2);
          ctx.stroke();
          break;
          
        case 'rectangle':
          this.clearCanvas();
          ctx.beginPath();
          ctx.rect(this.data.startX, this.data.startY, x - this.data.startX, y - this.data.startY);
          ctx.stroke();
          break;
      }
      
      this.setData({
        startX: x,
        startY: y
      });
    }
  },

  touchEnd() {
    if (e.touches.length === 0) {
      this.setData({
        isDrawing: false,
        lastScale: this.data.scale
      });
    }
  },

  switchTool(e) {
    const tool = e.currentTarget.dataset.tool;
    this.setData({
      currentTool: tool
    });
  },

  showColorPicker() {
    this.setData({
      showColorPicker: !this.data.showColorPicker,
      showSizePicker: false
    });
  },

  showSizePicker() {
    this.setData({
      showSizePicker: !this.data.showSizePicker,
      showColorPicker: false
    });
  },

  selectColor(e) {
    const color = e.currentTarget.dataset.color;
    this.setData({
      currentColor: color,
      showColorPicker: false
    });
    this.ctx.strokeStyle = color;
  },

  selectSize(e) {
    const size = e.currentTarget.dataset.size;
    this.setData({
      lineWidth: size,
      showSizePicker: false
    });
    this.ctx.lineWidth = size;
  },

  clearCanvas() {
    const ctx = this.ctx;
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  },

  saveCanvas() {
    wx.canvasToTempFilePath({
      canvas: this.canvas,
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            });
          },
          fail: (err) => {
            if (err.errMsg.includes('auth deny')) {
              wx.showModal({
                title: '提示',
                content: '需要您授权保存图片到相册',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting({
                      success: (settingRes) => {
                        if (settingRes.authSetting['scope.writePhotosAlbum']) {
                          this.saveCanvas();
                        }
                      }
                    });
                  }
                }
              });
            } else {
              wx.showToast({
                title: '保存失败',
                icon: 'error'
              });
            }
          }
        });
      },
      fail: () => {
        wx.showToast({
          title: '生成图片失败',
          icon: 'error'
        });
      }
    });
  }
}); 